<template>
	<view class="wrap">
		<que-nav :loreName="loreName" :taskName="taskName" @backUp="backUp"></que-nav>
		<!-- 答题进度 -->
		<exam-progress :currPercent="currPercent" :queLen="queLen"></exam-progress>
		<view class="quesWrap padd">
			<view class="innerQues"
				v-for="(item,index) in queList"
				:key="index"
				v-show="(index+1) == currIndex"
			>
				<que-item 
					:item="item" 
					:index="index" 
					:currIndex="currIndex" 
					@selectOption="selectOption"
					@selectMultiOption="selectMultiOption"
					@selectTkOpt="selectTkOpt"
				></que-item>
			</view>
		</view>
		<!-- 底部按钮动作 -->
		<que-btn
			:currPage="currPage"
			:btnTit="btnTit"
			:ansRightNum="ansRightNum" 
			:ansErrNum="ansErrNum" 
			:currIndex="currIndex"
			:queLen="queLen"
			:lastQueFlag="lastQueFlag"
			:isDisableFlag="isDisableFlag"
			:completeStatus="completeStatus"
			@submitQueRes="submitQueRes"
			@goNextQue="goNextQue"
			@lastSubmitQueRes="lastSubmitQueRes"
			@showQueCard="showQueCard" 
		></que-btn>
		<!-- 答题卡 -->
		<tui-bottom-popup :show="popupShow" :radius="radius" @close="hidePopup">
			<view class="popuoView">
				<template v-if="popOpt == 'queCard'">
					<que-card :currIndex="currIndex" :queList="queList" :queLen="queLen" @switchQue="switchQue"></que-card>
				</template>
				<template v-else-if="popOpt == 'queRes'">
					<que-res :ansRightFlag="ansRightFlag" :jfNum="jfNum"></que-res>
				</template>
			</view>
		</tui-bottom-popup>
	</view>
</template>

<script>
	import QueNav from './components/QueNav'
	import ExamProgress from './components/ExamProgress'
	import QueItem from './components/QueItem'
	import QueBtn from './components/QueBtn'
	import QueCard from './components/QueCard'
	import QueRes from './components/QueRes'
	import { insertStudyInfo,updateLogStatus } from '@/api/zhuxue'
	import zhuxueUtils from '@/common/zhuxueUtils.js'
	export default {
		components:{
			QueNav,
			ExamProgress,
			QueItem,
			QueBtn,
			QueCard,
			QueRes
		},
		data() {
			return {
				loreName:'',
				taskName:'',
				studyLogId:0,
				loreId:0,
				originLoreId:0,
				currSubId:0,
				currPercent:0,
				percentIndex:0,
				currIndex:1,
				ansRightNum:0,
				ansErrNum:0,
				queLen:0,
				popupShow:false,
				radius:true,
				popOpt:'',//queCard queRes
				ansRightFlag:null,//回答正确/错误的flag 用于显示底部弹层(每道题)
				btnTit:'提交',
				queList:[],
				isDisableFlag:false,//每道题提交的disabled状态
				completeStatus:-1,//记录每道题的是否已做0 未做 1已做
				lastQueFlag:false,//是否为最后一题标识
				multiArr:[],//用于存储多选题的选项
				jfNum:0,
				nextLoreIdStr:'',
				currentAllQuestionFlag:1,//全部作对为1 否则为0
				currPage:'quePage',
				currentLoreId:0
			}
		},
		onLoad(options){
			this.loreName = options.loreName;
			this.taskName = options.taskName;
			this.currSubId = options.currSubId;
			this.studyLogId = options.studyLogId;
			this.loreId = options.loreId;
			this.originLoreId = options.loreId;
			this.nextLoreIdStr = options.nextLoreIdStr;
			this.currentLoreId = options.currentLoreId;
			this.queList = uni.getStorageSync('zxQueList');
			this.queLen = this.queList.length;
			this.completeStatus = this.queList[0].completeStatus;
			var tmpRightArray = this.queList.filter(item=>{
				return item.completeStatus == 1 && item.result == 1
			});
			var tmpErrArray = this.queList.filter(item=>{
				return item.completeStatus == 1 && item.result == 0
			});
			this.ansRightNum = tmpRightArray.length;
			this.ansErrNum = tmpErrArray.length;
			if(this.ansErrNum > 0){
				this.currentAllQuestionFlag *= 0;
			}else{
				this.currentAllQuestionFlag *= 1;
			}
			this.percentIndex = Number(this.ansRightNum) + Number(this.ansErrNum);
			this.currPercent = (this.percentIndex/this.queLen)*100;
			if(this.completeStatus == 1){
				if(this.queList.length == 1){
					this.btnTit = '做完了';
					this.lastQueFlag = true;
				}else{
					this.btnTit = '进入下一题';
				}
			}else{
				this.btnTit = '提交';
			}
		},
		methods: {
			//提交动作
			submitQueRes(){
				console.log('开始提交=' + this.util.getNowTime());
				var tmpIndex = Number(this.currIndex-1);
				var dxFlag = true,multiResFlag = true,tkResFlag = true;
				var tmpList = this.queList[tmpIndex];
				if(tmpList.lqType == '单选题' || tmpList.lqType == '判断题'){
					if(tmpList.currAns == ''){
						this.util.showToast('请选择答案');
						dxFlag = false;
						return;
					}
				}else if(tmpList.lqType == '多选题'){
					if(this.multiArr.length == 0){
						this.util.showToast('请完善选项答案');
						multiResFlag = false;
						return;
					}
					tmpList.currAns = this.multiArr.join(',');
				}else if(tmpList.lqType == '填空选择题'){
					var tmpTkArr = tmpList.tkOptIndexArr;
					for(var i=0;i<tmpTkArr.length;i++){
						if(tmpTkArr[i].tkIndex == -1){
							tkResFlag = false;
						}
					}
					if(!tkResFlag){
						this.util.showToast('请完善选项答案');
						return;
					}
					const newArr = tmpTkArr.map(item=>{
						return item.value;
					});
					tmpList.currAns = newArr.join(',');
				}
				console.log('转换开始=' + this.util.getNowTime());
				var answerOptionArrayStr = zhuxueUtils.arrayToJson(tmpList.answerOptionArray);
				console.log(tmpList.answerOptionArray);
				console.log(answerOptionArrayStr);
				console.log('转换结束=' + this.util.getNowTime());
				var field = { account:uni.getStorageSync('token'),studyLogId:this.studyLogId,loreId:this.loreId,subId:this.currSubId,currentLoreId:this.currentLoreId,answerOptionArrayStr:answerOptionArrayStr,questionStep:this.currIndex,myAnswer:tmpList.currAns,lqId:tmpList.lqId,loreTaskName:this.taskName };
				let contentStr = this.crypto.encrypt(JSON.stringify( field )); 
				console.log('组装数据=' + this.util.getNowTime());
				//console.log(field)
				this.isDisableFlag = true;
				this.btnTit = '提交中...';
				this.popOpt = 'queRes';
				console.log('请求=' + this.util.getNowTime());
				insertStudyInfo({content:contentStr}).then(res=>{
					console.log('成功=' + this.util.getNowTime());
					//console.log(res)
					var studyResult = res.data.datas.studyResult;
					this.jfNum = res.data.datas.coin;
					this.popupShow = true;
					if(studyResult == 1){//做对
						this.ansRightFlag = true;
						this.ansRightNum+=1;
						this.$set(tmpList,'result',1);
						this.currentAllQuestionFlag *= 1;
					}else{//做错
						this.ansRightFlag = false;
						this.ansErrNum+=1;
						this.$set(tmpList,'result',0);
						this.currentAllQuestionFlag *= 0;
					}
					this.percentIndex++;
					this.currPercent = Number(  this.percentIndex/this.queLen )*100;
					if(tmpList.lqType == '单选题' || tmpList.lqType == '判断题'){//更新当前的索引
						tmpList.myAnsSingleIndex = tmpList.optIndex;
					}else if(tmpList.lqType == '多选题'){//selFLag
						var myAnsIndexArr = [];
						for(var k=0;k<this.multiArr.length;k++){
							myAnsIndexArr.push(zhuxueUtils.transOptToNums(this.multiArr[k]));
						}
						for(var f=0;f<tmpList.multiOptIndexArr.length;f++){
							for(var g=0;g<myAnsIndexArr.length;g++){
								if(f == myAnsIndexArr[g]){
									tmpList.multiOptIndexArr[f].selFlag = true;
								}
							}
						}
					}
					setTimeout(()=>{
						tmpList.completeStatus = 1;
						this.completeStatus = 1;
						this.isDisableFlag = false;
						this.popupShow = false;
						//this.jfNum = 0;
						this.multiArr = [];
						// if(studyResult == 1){
						// 	this.currIndex ++;
						// 	var tmpListSp = this.queList[this.currIndex];
						// 	this.completeStatus = tmpListSp.completeStatus;//更新completeStatus状态
						// }
						if(this.currIndex == this.queLen){
							this.lastQueFlag = true;
							this.btnTit = '做完了';
						}else{
							this.btnTit = '进入下一题'
						}
					},1200);
				}).catch(err=>{
					console.log(err)
					this.btnTit = '提交';
					this.isDisableFlag = false;
				});
			},
			//进入下一题
			goNextQue(){
				var tmpList = this.queList[this.currIndex];
				this.completeStatus = tmpList.completeStatus;//更新completeStatus状态
				this.currIndex ++; 
				if(this.completeStatus == 0){
					this.btnTit = '提交';
				}else{
					if(this.currIndex == this.queLen && tmpList.result >= 0){
						this.lastQueFlag = true;
						this.btnTit = '做完了';
					}else{
						this.btnTit = '进入下一题';
					}
				}
			},
			//最后提交更新当前学习状态
			lastSubmitQueRes(){
				var studyLogId_curr = 0;
				var step_new = 0;
				if(this.percentIndex == this.queLen){
					var tmpList = this.queList[0];
					var loreTypeName = tmpList.loreType,currentLoreId = this.currentLoreId;
					if(loreTypeName == '针对性诊断'){
						if(this.currentAllQuestionFlag == 1){//表示当前题型全部正确
							//access:1--当前级全部正确，2:当前级部分正确或者无正确
							//step1:诊断时如果是本知识典直接全部正确，那么修改isfinish为2，stepComplete为1，access为1
							//step2:诊断时如果是关联知识点当前级全部正确。（转向学习状态）isfinish为1，stepComplete为1，access为1
							//step=0:表示不修改step的值
							if(currentLoreId == this.originLoreId){//本知识点全部正确
								//studyLogId_curr = await this.updateLogStatus(0,1,2,1,currentLoreId,loreTypeName);
								this.updateLogStatus(0,1,2,1,currentLoreId,loreTypeName);
							}else{//是关联知识点当前级全部正确，需要走到第三阶段，关联性诊断的学习阶段
								//studyLogId_curr = await this.updateLogStatus(0,1,1,1,currentLoreId,loreTypeName);
								this.updateLogStatus(0,1,1,1,currentLoreId,loreTypeName);
							}
						}else{//表示当前题型没有全部正确(继续往下级子知识点)
							var lorePath = uni.getStorageSync('lorePath');
							//console.log(lorePath)
							if(zhuxueUtils.checkLoreId(lorePath,currentLoreId)){
								//表示返钱知识点的关联性诊断已经完成，需要走到第三阶段，关联性诊断的学习阶段
								//studyLogId_curr = await this.updateLogStatus(0,1,1,2,currentLoreId,loreTypeName);
								this.updateLogStatus(0,1,1,2,currentLoreId,loreTypeName)
							}else{//第1个参数表示：当前知识点的关联性诊断还未完成
								this.updateLogStatus(0,0,1,2,currentLoreId,loreTypeName);
							}
						}
					}else{//再次诊断
						if(currentLoreId == this.originLoreId){
							step_new = 4;
						}else{
							step_new = 3;
						}
						if(this.currentAllQuestionFlag == 1){//表示当前题型全部正确
							//step:stepComplete:isFinish:access
							//studyLogId_curr = await this.updateLogStatus(step_new,0,1,1,currentLoreId,loreTypeName);
							this.updateLogStatus(step_new,0,1,1,currentLoreId,loreTypeName);
						}else{
							//studyLogId_curr = await this.updateLogStatus(step_new,0,1,2,currentLoreId,loreTypeName);//部分正确，需要进入5部学习法
							this.updateLogStatus(step_new,0,1,2,currentLoreId,loreTypeName);//部分正确，需要进入5部学习法
						}
					}
					// console.log('currentAllQuestionFlag=' + this.currentAllQuestionFlag)
					// //console.log('studyLogId_curr=' + studyLogId_curr);
					// console.log('currentLoreId=' + currentLoreId)
					// console.log('originLoreId=' + this.originLoreId)
					// console.log('loreTypeName=' + loreTypeName)
					// console.log('lorePath=' + lorePath)
				}else{
					this.util.showToast('存在尚未完成的试题');
				}
			},
			/**
				当前阶段完成，修改指定logId的isFinish状态、stepComplete状态，access状态
				stepComplete:该阶段完成状态0：未完成，1：完成
				isFinish:该知识点完成状态1：未完成，2：完成
				access：该阶段关联知识点完成状态0：未完成，1：完成
			**/
			updateLogStatus(step,stepComplete,isFinish,access,currentLoreId,loreTypeName){
				var submitType = '';
				var studyLogId_curr = 0;
				if(loreTypeName == '针对性诊断'){
					submitType = 'zdxzd';
				}else if(loreTypeName == '再次诊断'){
					submitType = 'againzd';
				}
				this.isDisableFlag = true;
				this.btnTit = '提交中...';
				var field = { account:uni.getStorageSync('token'),studyLogId:this.studyLogId,loreId:this.originLoreId,submitType:submitType,
							currentStepLoreIdStr:this.nextLoreIdStr,step:step,access:access,currentLoreId:currentLoreId,isFinish:isFinish,stepComplete:stepComplete};
				let contentStr = this.crypto.encrypt(JSON.stringify( field )); 
				//console.log(field)
				updateLogStatus({content:contentStr}).then(res=>{
					//console.log(res)
					this.originLoreId = res.data.datas.loreId;
					studyLogId_curr = res.data.datas.studyLogId;
					uni.navigateTo({
						url:'/pages/subIndex/traceBack/traceBack?studyLogId=' + studyLogId_curr + '&loreId=' + this.originLoreId + '&fromPage=quePage',
						success:()=>{
							uni.removeStorageSync('zxQueList');
						}
					})
				}).catch(err=>{
					this.btnTit = '做完了';
					this.isDisableFlag = false;
					console.log(err)
				});
			},
			//填空选择题每一项的点击
			selectTkOpt(index,ansNumIndex,jjIndex){
				//Vue.set( target, key, value )
				// target：要更改的数据源(可以是对象或者数组)
				// key：要更改的具体数据
				// value ：重新赋的值
				//this.$set(this.queList[index].tkOptIndexArr,ansNumIndex,jjIndex);//数组
				// this.$set(this.queList[index].tkOptIndexArr[ansNumIndex],'tkIndex',jjIndex)//对象
				var item = this.queList[index];
				this.$set(item.tkOptIndexArr[ansNumIndex],'tkIndex',jjIndex)//对象
				//this.$set(item.tkOptIndexArr[ansNumIndex],'value',item.answerOptionArray[jjIndex]);
				item.tkOptIndexArr[ansNumIndex].value = zhuxueUtils.transOptToWords(jjIndex);
			},
			//多选题点击某几项
			selectMultiOption(index,innerIndex,myAns){
				var item = this.queList[index].multiOptIndexArr[innerIndex];
				if(item.selFlag == true){
					this.$set(item,'selFlag',false);
					for(var i=0;i<this.multiArr.length;i++){
						if(myAns == this.multiArr[i]){
							this.multiArr.splice(i,1);
						}
					}
				}else if(item.selFlag == false){
					this.$set(item,'selFlag',true)
					this.multiArr.push(myAns);
				}
			},
			//单选题/判断题点击某一项赋予active
			selectOption(index,currNum,myAns){
				this.queList[index].optIndex = currNum;
				this.queList[index].currAns = myAns;
			},
			//答题卡弹层
			showQueCard(){
				this.popOpt = 'queCard';
				this.radius = true;
				this.popupShow = true;
			},
			switchQue(nextIndex,index){
				this.popupShow = false;
				this.currIndex = nextIndex;
				var tmpList = this.queList[this.currIndex-1];
				this.completeStatus = tmpList.completeStatus;
				if(this.completeStatus == 0){
					this.btnTit = '提交';
				}else{
					if(this.currIndex == this.queLen && tmpList.result >= 0){
						this.lastQueFlag = true;
						this.btnTit = '做完了';
					}else{
						this.lastQueFlag = false;
						this.btnTit = '进入下一题';
					}
				}
			},
			hidePopup(){
				this.popupShow = false;
			},
			backUp(){
				uni.navigateBack({delta:1})
			}
		}
	}
</script>

<style lang="scss">
	.wrap{
		padding-bottom: 140rpx;
	}
	page{
		background: $pss-bg-primary;
		@include respTo(phone){
			margin-top: calc(200rpx + var(--status-bar-height));
		}
		@include respTo(pad){
			margin-top: calc(160rpx + var(--status-bar-height));
		}
	}
</style>
